<template>
  <a-layout style="min-height: 100vh">
    <!-- 左侧导航 -->
    <a-layout>
      <a-layout-content style="padding: 20px; display: flex;">
        <!-- 左侧主要区域 -->
        <div class="left-content">
          <UserInfo />
          <ResourceSection
            :chapters="chapters"
            :activeChapter="activeChapter"
            :resources="resources"
            :updates="updates"
            @show-add-chapter="isAddChapterModalVisible = true"
            @show-add-resource="isAddResourceModalVisible = true"
            @delete-chapter="deleteChapter"
            @select-resource="handleSelectResource"
            @edit-resource="handleEditResource"
            @update:activeChapter="activeChapter = $event"
          />
        </div>

        <!-- 右侧次要区域 -->
        <div class="right-content">
          <WeatherCard :weatherData="weatherInforObj" />
          <StudentQuestions :questions="questions" />
        </div>
      </a-layout-content>
    </a-layout>

    <!-- 模态框及抽屉 -->
    <AddChapterModal
      :visible="isAddChapterModalVisible"
      @add-chapter="handleAddChapter"
      @update:visible="isAddChapterModalVisible = $event"
    />
    <AddResourceModal
      :visible="isAddResourceModalVisible"
      @add-resource="handleAddResource"
      @update:visible="isAddResourceModalVisible = $event"
    />
    <a-modal
      v-model:visible="isEditResourceModalVisible"
      title="编辑资源"
      @ok="handleUpdateResource"
      @cancel="isEditResourceModalVisible = false"
    >
      <a-form layout="vertical">
        <a-form-item label="标题">
          <a-input v-model:value="editingResource.title" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="editingResource.description" />
        </a-form-item>
        <a-form-item label="类型">
          <a-select v-model:value="editingResource.type">
            <a-select-option value="ppt">PPT</a-select-option>
            <a-select-option value="transcript">讲稿</a-select-option>
            <a-select-option value="plan">教案</a-select-option>
            <a-select-option value="media">多媒体</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <ResourcePanel
      :visible="isResourcePanelVisible"
      :resource="currentResource"
      :files="files"
      :selectedFile="selectedFile"
      @close="closeResourcePanel"
      @select-file="selectFile"
      @show-add-file="isAddFileModalVisible = true"
      @deselect-file="deselectFile"
      @save-teaching-plan="saveTeachingPlan"
      @delete-resource="deleteResource"
      @delete-file="deleteFile"
      @send-to-assistant="handleSendToAssistant"
      @restore-version="handleRestoreVersion"
      @update:visible="isResourcePanelVisible = $event"
    />
    <AddFileModal
      ref="addFileModal"
      :visible="isAddFileModalVisible"
      :currentType="currentResource ? currentResource.type : ''"
      @update-analysis="updateFileAnalysis"
      @add-file="handleAddFile"
      @update:visible="isAddFileModalVisible = $event"
    />
  </a-layout>
</template>

<script>
import axios from 'axios';
import UserInfo from "@/components/Manage/UserInfo.vue";
import ResourceSection from "@/components/Manage/ResourceSection.vue";
import WeatherCard from "@/components/Manage/WeatherCard.vue";
import StudentQuestions from "@/components/Manage/StudentQuestions.vue";
import ResourcePanel from "@/components/Manage/ResourcePanel.vue";
import AddChapterModal from "@/components/Manage/AddChapterModal.vue";
import AddResourceModal from "@/components/Manage/AddResourceModal.vue";
import AddFileModal from "@/components/Manage/AddFileModal.vue";
import { FileOutlined, FileTextOutlined, CalendarOutlined, VideoCameraOutlined } from '@ant-design/icons-vue';

export default {
  name: "ManageHome",
  components: {
    UserInfo,
    ResourceSection,
    WeatherCard,
    StudentQuestions,
    ResourcePanel,
    AddChapterModal,
    AddResourceModal,
    AddFileModal
  },
  data() {
    return {
      weatherInforObj:{},
      activeChapter: null,
      chapters: [],
      resources: [],
      updates: [],
      questions: [],
      files: [],
      isAddChapterModalVisible: false,
      isAddResourceModalVisible: false,
      isEditResourceModalVisible: false,
      isResourcePanelVisible: false,
      isAddFileModalVisible: false,
      currentResource: null,
      selectedFile: null,
      editingResource: {
        id: null,
        title: '',
        description: '',
        type: ''
      },
      fileFormData: new FormData(),
      apiConfig: {
        baseUrl: 'http://localhost:8000',
        endpoints: {
          chapters: '/api/chapters/',
          resources: '/api/resources/',
          files: '/api/files/',
          updates: '/api/updates/',
          questions: '/api/questions/'
        }
      }
    };
  },
  methods: {
    async handleRestoreVersion(versionData) {
      try {
        const formData = new FormData();
        formData.append('version_id', versionData.version_id);

        const response = await axios.post(
          `${this.apiConfig.baseUrl}${this.apiConfig.endpoints.files}${this.selectedFile.id}/restore_version/`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': `Token ${localStorage.getItem('token')}`
            }
          }
        );
        
        this.$message.success('版本恢复成功');
        await this.fetchFilesByResource(this.currentResource.id);
        this.selectedFile = response.data;
      } catch (error) {
        console.error('恢复版本失败:', error);
        this.$message.error(error.response?.data?.error || '恢复版本失败');
      }
    },
    async recordUpdate(action, target, details = '') {
      try {
        const message = `${action === 'add' ? '添加' : action === 'delete' ? '删除' : '更新'}了${target}: ${details}`;
        await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates, {
          message,
        });
        const updatesRes = await axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates);
        this.updates = updatesRes.data.slice(0, 10);
      } catch (error) {
        console.error('记录更新日志失败:', error);
      }
    },
    async fetchData() {
      try {
        const [chaptersRes, questionsRes, updatesRes] = await Promise.all([
          axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.chapters),
          axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.questions),
          axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates)
        ]);
        this.chapters = chaptersRes.data;
        this.questions = questionsRes.data;
        this.updates = updatesRes.data;

        if (this.chapters.length > 0) {
          this.activeChapter = this.chapters[0].id;
        await this.fetchResourcesByChapter(this.activeChapter);
        }
      } catch (error) {
        console.error('数据加载失败:', error);
        }
    },

    async fetchResourcesByChapter(chapterId) {
      try {
        const res = await axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.resources + `?chapter=${chapterId}`);
        this.resources = res.data;
      } catch (error) {
        console.error('资源加载失败:', error);
      }
    },

    async fetchFilesByResource(resourceId) {
      try {
        const res = await axios.get(this.apiConfig.baseUrl + this.apiConfig.endpoints.files + `?resource=${resourceId}`);
        this.files = res.data;
      } catch (error) {
        console.error('文件加载失败:', error);
        this.$message.error('加载文件失败');
      }
    },

    async handleAddChapter(chapter) {
      try {
        await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.chapters, { name: chapter.name });
        await this.recordUpdate('add', '章节', chapter.name);
    this.fetchData();
        this.isAddChapterModalVisible = false;
      } catch (error) {
        console.error('添加章节失败:', error);
  }
    },

    async deleteChapter(chapterId) {
      try {
        if (this.chapters.length <= 1) {
          alert("至少要保留一个章节！");
          return;
        }

        const chapter = this.chapters.find(c => c.id === chapterId);
        if (!chapter) {
          this.$message.error('未找到要删除的章节');
          return;
        }

        await axios.delete(this.apiConfig.baseUrl + this.apiConfig.endpoints.chapters + `${chapterId}/`);
        await this.recordUpdate('delete', '章节', chapter.name);
    this.fetchData();
      } catch (error) {
        console.error('删除章节失败:', error);
        this.$message.error('删除章节失败');
  }
    },

    getIconComponent(type) {
      const iconMap = {
        ppt: FileOutlined,
        transcript: FileTextOutlined,
        plan: CalendarOutlined,
        media: VideoCameraOutlined
};
      return iconMap[type] || FileOutlined;
    },

    async handleAddResource(resource) {
      try {
        if (!this.activeChapter) {
          this.$message.error('请先选择章节');
          return;
        }

        if (!resource.title || !resource.type) {
          this.$message.error('标题和类型是必填项');
          return;
        }

        const iconComponent = this.getIconComponent(resource.type);
        const iconName = iconComponent.name || iconComponent.__name;

        const requestData = {
          title: resource.title,
          description: resource.description || '',
          type: resource.type,
          chapter: this.activeChapter,
          icon_name: iconName
        };

        const response = await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.resources, requestData);
        await this.recordUpdate('add', `${resource.type}资源`, resource.title);
        this.resources = [...this.resources, response.data];
        this.isAddResourceModalVisible = false;
        this.$message.success('资源添加成功！');
        await this.fetchResourcesByChapter(this.activeChapter);
      } catch (error) {
        console.error('添加资源失败:', error);
        let errorMsg = '添加资源失败';
        if (error.response) {
          errorMsg = `错误: ${JSON.stringify(error.response.data)}`;
        }
        this.$message.error(errorMsg);
      }
    },

    async deleteResource(resourceId) {
      try {
        const resource = this.resources.find(r => r.id === resourceId);
        await axios.delete(this.apiConfig.baseUrl + this.apiConfig.endpoints.resources + `${resourceId}/`);
        await this.recordUpdate('delete', `${resource.type}资源`, resource.title);
        this.$message.success('资源删除成功');
        this.closeResourcePanel();
        await this.fetchResourcesByChapter(this.activeChapter);
      } catch (error) {
        console.error('删除资源失败:', error);
        this.$message.error('删除资源失败');
      }
    },

    handleEditResource(resource) {
      this.editingResource = {
        id: resource.id,
        title: resource.title,
        description: resource.description,
        type: resource.type
      };
      this.isEditResourceModalVisible = true;
    },

    async handleUpdateResource() {
      try {
        const { id, ...updateData } = this.editingResource;
        await axios.patch(this.apiConfig.baseUrl + this.apiConfig.endpoints.resources + `${id}/`, updateData);
        await this.recordUpdate('update', `${this.editingResource.type}资源`, this.editingResource.title);
        this.$message.success('资源更新成功');
        this.isEditResourceModalVisible = false;
        await this.fetchResourcesByChapter(this.activeChapter);
      } catch (error) {
        console.error('更新资源失败:', error);
        this.$message.error('更新资源失败');
      }
    },

    async handleSelectResource(resource) {
      this.currentResource = resource;
      await this.fetchFilesByResource(resource.id);
      this.isResourcePanelVisible = true;
      this.selectedFile = null;
    },

    closeResourcePanel() {
      this.isResourcePanelVisible = false;
      this.currentResource = null;
      this.selectedFile = null;
    },

    selectFile(file) {
      this.selectedFile = file;
    },

    deselectFile() {
      this.selectedFile = null;
    },

    async saveTeachingPlan(plan) {
      try {
        if (this.selectedFile && this.selectedFile.type === "transcript") {
          const formData = new FormData();
          formData.append('json_data', JSON.stringify(plan));

          await axios.post(
            `${this.apiConfig.baseUrl}${this.apiConfig.endpoints.files}${this.selectedFile.id}/update_json/`,
            formData,
            {
              headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': `Token ${localStorage.getItem('token')}`
              }
            }
          );
          
          await this.recordUpdate('update', '讲稿文件', this.selectedFile.name);
          await this.fetchFilesByResource(this.currentResource.id);
          this.$message.success("教学方案已保存并创建新版本！");
        }
      } catch (error) {
        console.error('保存教学计划失败:', error.response?.data || error);
        this.$message.error(`保存失败: ${error.response?.data?.message || error.message}`);
      }
    },

    async handleAddFile(fileData) {
      try {
        if (!this.currentResource?.id) {
          this.$message.error('请先选择资源');
          return;
        }
        if (!fileData?.file) {
          this.$message.error('无效的文件数据');
          return;
        }

        const formData = new FormData();
        formData.append('file', fileData.file);
        formData.append('name', fileData.name || fileData.file.name || '未命名文件');
        formData.append('type', fileData.type || this.currentResource.type);
        formData.append('resource', this.currentResource.id);
        
        // Add content only if available
        if (fileData.content) {
          formData.append('content', fileData.content);
        }

        const response = await axios.post(
          `${this.apiConfig.baseUrl}${this.apiConfig.endpoints.files}`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Authorization': `Token ${localStorage.getItem('token')}` // Add auth if needed
            }
          }
        );
        
        this.isAddFileModalVisible = false;
        this.$message.success('文件上传成功！');
        
        // 2. Refresh file list
        await this.fetchFilesByResource(this.currentResource.id);
        
        // 3. Start async analysis
        this.$refs.addFileModal.handleAddNewFile(fileData.file)
          .then(analysisData => {
            const newFile = this.files.find(f => f.name === fileData.name);
            if (newFile) {
              this.updateFileAnalysis(newFile.id, analysisData);
            }
          })
          .catch(error => {
            console.error('分析失败:', error);
            this.$message.warning('文件分析处理中，请稍后刷新查看结果');
          });

        await this.recordUpdate('add', `${this.currentResource.type}文件`, fileData.name);

      } catch (error) {
        console.error('上传失败:', error.response?.data || error);
        this.$message.error(`上传失败: ${error.response?.data?.message || error.message}`);
      }
    },

    async updateFileAnalysis(fileId, analysisData) {
      try {
        const formData = new FormData();
        console.log(analysisData)
        formData.append('json_data', JSON.stringify(analysisData));

        const response = await axios.post(
          `${this.apiConfig.baseUrl}${this.apiConfig.endpoints.files}${fileId}/update_json/`,
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        );

        await this.fetchFilesByResource(this.currentResource.id);
        return response.data;
      } catch (error) {
        console.error('更新分析结果失败:', error.response?.data || error);
        throw error;
      }
    },
    async deleteFile(fileId) {
      try {
        const file = this.files.find(f => f.id === fileId);
        await axios.delete(this.apiConfig.baseUrl + this.apiConfig.endpoints.files + `${fileId}/`);
        await this.recordUpdate('delete', `${file.type}文件`, file.name);

        await this.fetchFilesByResource(this.currentResource.id);

        if (this.selectedFile?.id === fileId) {
          this.selectedFile = null;
        }

        this.$message.success('文件删除成功');
      } catch (error) {
        console.error('删除文件失败:', error);
        this.$message.error('删除文件失败');
      }
    },

    handleSendToAssistant(fileData) {
      this.$router.push({
        name: 'ChatView',
        query: {
          fileId: fileData.fileId,
          fileName: fileData.fileName
        },
        state: {
          fileContent: fileData.fileContent
        }
      });
    }
  },
  watch: {
    async activeChapter(newVal) {
      if (newVal) {
        await this.fetchResourcesByChapter(newVal);
      }
    }
  },
  created() {
    this.fetchData();
  }
};
</script>

<style scoped>
.left-content {
  flex: 2;
  padding-right: 20px;
  min-width: 0;
}

.right-content {
  flex: 1;
}
</style>

